package com.wash.shoes.domain.dy.request;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import cn.hutool.core.util.IdUtil;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.mapper.BrandMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.douyin.openapi.client.Client;
import com.douyin.openapi.client.models.OauthClientTokenRequest;
import com.douyin.openapi.client.models.OauthClientTokenResponse;
import com.douyin.openapi.credential.models.Config;
import com.wash.shoes.common.property.DyProperty;
import com.wash.shoes.domain.dy.model.SaveDyModel;
import com.wash.shoes.domain.dy.model.ServiceUpdateDto;
import com.wash.shoes.entity.BrandPo;
import com.wash.shoes.service.*;

import cn.hutool.core.lang.Assert;
import lombok.extern.log4j.Log4j2;

/**
 * @author lijianguo
 * @Date 17/03/2025 14:12 dy token的处理
 **/
@Log4j2
@Component
public class DyBaseRequest {

    @Autowired
    protected BrandService brandService;
    @Autowired
    protected FactoryAreaConfigService factoryAreaConfigService;
    @Autowired
    protected ShopService shopService;
    @Resource
    DyProperty dyProperty;
    @Resource
    OrderGoodService orderGoodService;
    @Resource
    OrderService orderService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 根据抖音账号 获取抖音的token信息
     * 
     * @param accountId 账号id
     * @return
     */
    public static String getDyTokenKeyWithAccountId(String accountId) {
        return DyConstant.REDIS_DY_TOKEN + ":" + accountId;
    }
    @Autowired
    private BrandMapper brandMapper;
    protected BrandPo getBrandPo(OrderPo orderPo) {
        BrandPo brandPo= brandMapper.selectById(orderPo.getBrandId());
        org.springframework.util.Assert.notNull(brandPo,"品牌不存在,brandId:"+ orderPo.getBrandId());
        return brandPo;
    }
    /**
     * @return 获取抖音的token 2个小时过期
     */
    public String getDyToken(String accountId) {
        String tokenCacheKey = getDyTokenKeyWithAccountId(accountId);
        String accessToken = (String)redisTemplate.opsForValue().get(tokenCacheKey);
        try {
            if (accessToken == null) {
                BrandPo brandPo = brandService.getOne(new LambdaQueryWrapper<BrandPo>().eq(BrandPo::getStatus, 1)
                    .eq(BrandPo::getAccountid, accountId).last("limit 1"));
                Assert.notNull(brandPo, "抖音账号不存在.accountid:" + accountId);
                /*                Config config =
                    new Config().setClientKey(dyProperty.getAppId()).setClientSecret(dyProperty.getAppSecret()); // 改成自己的app_id跟secret
                Client client = new Client(config);
                OauthClientTokenRequest sdkRequest = new OauthClientTokenRequest();
                sdkRequest.setClientKey(dyProperty.getAppId());
                sdkRequest.setClientSecret(dyProperty.getAppSecret());*/

                Config config = new Config().setClientKey(brandPo.getAppid()).setClientSecret(brandPo.getAppsecret()); // 改成自己的app_id跟secret
                Client client = new Client(config);
                OauthClientTokenRequest sdkRequest = new OauthClientTokenRequest();
                sdkRequest.setClientKey(brandPo.getAppid());
                sdkRequest.setClientSecret(brandPo.getAppsecret());

                sdkRequest.setGrantType("client_credential");
                sdkRequest.setHeader(new HashMap<>());
                OauthClientTokenResponse sdkResponse = client.OauthClientToken(sdkRequest);
                log.info("getDyToken accountId:{},resp:{}",accountId,sdkResponse.toString());
                accessToken = sdkResponse.data.accessToken;
                redisTemplate.opsForValue().set(tokenCacheKey, accessToken, 3000, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            log.error(e);
        }
        return accessToken;
    }

    /**
     * @author lijianguo
     * @Date 19/03/2025 post请求数据
     **/
    public String postRequest(String url, Object object,String accountId) {

        HttpHeaders headers = new HttpHeaders();
//        if (object instanceof BaseDyModel) {
//            BaseDyModel saveDyModel = (BaseDyModel)object;
            // 设置 token 到请求头
            headers.set("access-token", getDyToken(accountId));
        /*} *//*else if (object instanceof ServiceUpdateDto) {
            ServiceUpdateDto saveDyModel = (ServiceUpdateDto)object;
            // 设置 token 到请求头
            headers.set("access-token", getDyToken(saveDyModel.getAccount_id()));
        }*/

        headers.setContentType(MediaType.APPLICATION_JSON);
        String traceId=IdUtil.fastSimpleUUID();
        // 创建请求体，使用 Map 来表示用户信息
        log.info("======================================================================================");
        log.info("traceId:{},:request params is:  {},header:{} ",traceId, JSONObject.toJSONString(object),headers);
        HttpEntity<Object> requestEntity = new HttpEntity<>(object, headers);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("traceId:{},post url is [{}] ",traceId, url);
        log.info("traceId:{},result info is: {}",traceId, result);
        log.info("======================================================================================");
        return result;
    }

    /**
     * @param url 请求的地址
     * @return 获取GET请求
     */
    public String getRequest(String url, String accountId) {
        HttpHeaders headers = new HttpHeaders();
        // 设置 token 到请求头
        headers.set("access-token", getDyToken(accountId));
        // 设置请求体的内容类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 创建 HttpEntity 对象，将请求头封装在一起，因为是 GET 请求，请求体为 null
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        // 发送 GET 请求并获取响应
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        // 输出响应状态码和响应体
        log.info("Response Status is : {}", response.getStatusCode());
        if (response.getBody() != null && response.getBody().length() < 100) {
            log.info("Response body  is : {}", response.getBody());
        }
        return response.getBody();
    }

}
